import {defineComponent} from 'friendly-petite-vue'


type ExcelPasterProps = {
    table: any
}


export default defineComponent<ExcelPasterProps>('ExcelPaster', props => {
    let pasteList = null

    return {
        template: `
        <div id="batchPaste" @mounted="mounted" style="display:none">
            <table v-once :id="datagridId" :lay-filter="datagridId"></table>
            <div v-once :id="toolbarId" style="display:none">
                <div class="layui-btn-container layui-inline">
                    <button v-for="btn in toolbarButtons"
                            class="layui-btn layui-btn-sm"
                            :class="{'layui-btn-primary': btn.isPrimary, 'layui-btn-danger': btn.isDanger}"
                            :lay-event="btn.id">{{ btn.text }}</button>
                </div>
            </div>
            <a ref="downloadTemplate" href="/cjCdwbh9Rel/downloadTemplate" target="_blank"></a>
        </div>
        `,
        data() {
            return {
                datagridId: '',
                toolbarId: '',
                enableExcelPaste: false
            }
        },
        mounted() {
            const {table} = props

            // initialize table
            pasteList = this.$layui.table.render({
                elem: `#${this.datagridId}`,
                toolbar: `#${this.toolbarId}`,
                height: 'full',
                limit: 10000,
                cols: [[
                    {type: 'numbers', title: '序号'},
                    {field: 'srcCdwbh9', title: '原客户编码前9位'},
                    {field: 'dstCdwbh9', title: '新客户编码前9位'}
                ]],
                data: []
            })
            // listen to click event of toolbar
            table.on(`toolbar(${this.datagridId})`, ({event}) => {
                this.handleToolbarClick(event)
            })

            let handlePasteExcel = createPasteExcelHandler(data => {
                this.$store.excelData = data.map(row => ({ srcCdwbh9: row[0], dstCdwbh9: row[1] }))
                pasteList.reload({data: store.excelData})
            })
            
            document.body.addEventListener('paste', evt => {
                if (this.enableExcelPaste) {
                    handlePasteExcel(evt)
                }
            })
        },
        methods: {
            handleToolbarClick(eventName) {
                if (eventName === 'downloadTemplate') {
                    this.$refs.downloadTemplate.click()
                }
                else if (eventName === 'clear') {
                    pasteList.reload({data: []})
                }
            }
        }
    }
})
